package com.ptl.bp.util;

import com.alibaba.excel.EasyExcel;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class ExcelUtils {

    /**
     * 导出数据到HTTP响应
     * @param response HTTP响应对象
     * @param fileName 下载文件名（不需要后缀）
     * @param data 导出的数据列表
     * @param clazz 数据类型
     * @param <T> 数据类型
     */
    public static <T> void exportExcel(HttpServletResponse response, String fileName, List<T> data, Class<T> clazz) {
        if (response == null) {
            throw new RuntimeException("HTTP响应不能为空");
        }

        if (fileName == null || fileName.trim().isEmpty()) {
            fileName = "export_data";
        }

        // 确保文件名有.xlsx后缀
        if (!fileName.toLowerCase().endsWith(".xlsx")) {
            fileName = fileName + ".xlsx";
        }

        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());

            ContentDisposition contentDisposition = ContentDisposition.attachment()
                    .filename(fileName, StandardCharsets.UTF_8)
                    .build();
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());

            // 设置跨域头
            // response.setHeader("Access-Control-Expose-Headers", HttpHeaders.CONTENT_DISPOSITION);

            EasyExcel.write(response.getOutputStream(), clazz)
                    .autoCloseStream(false) // 防止EasyExcel自动关闭流
                    .sheet()
                    .doWrite(data);

        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }

    public static void validExcelFile(MultipartFile file) {
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("导入文件不能为空");
        }
        // 获取文件名并校验后缀名
        String filename = file.getOriginalFilename();
        if (filename == null || !filename.toLowerCase().endsWith(".xlsx")) {
            throw new RuntimeException("请上传.xlsx格式的Excel文件");
        }
    }
}